package com.solocredit.finance.ui.steps.fm

import android.Manifest
import android.app.Activity.RESULT_OK
import android.content.Intent
import android.graphics.Color
import android.graphics.Typeface
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.text.style.StyleSpan
import android.view.LayoutInflater
import android.view.View
import androidx.activity.result.ActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import com.solocredit.finance.R
import com.solocredit.finance.base.utils.ImageUtil
import com.solocredit.finance.base.utils.log.MullaLog
import com.solocredit.finance.base.utils.permission.OnPermissionCallback
import com.solocredit.finance.base.utils.permission.Permission
import com.solocredit.finance.base.utils.permission.XXPermissions
import com.solocredit.finance.databinding.FmMullaStepSelfieBinding
import com.solocredit.finance.http.ApiService
import com.solocredit.finance.http.ApiService.addCommonParams
import com.solocredit.finance.http.ApiService.addRandomParams
import com.solocredit.finance.http.HttpHelper
import com.solocredit.finance.mvp.ProFm
import com.solocredit.finance.ui.steps.act.MullaCameraSelfieAct
import com.solocredit.finance.ui.steps.act.MullaStepsAct
import com.solocredit.finance.utils.dialog.PermissionReasonDialog
import com.solocredit.finance.utils.dialog.VerificationSendSuccessDialog
import com.solocredit.finance.utils.event.MullaBehaviorTracker
import com.solocredit.finance.utils.event.MullaEventType
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.json.JSONArray
import org.json.JSONObject

/**
 * MullaFlow
 * @Author wwdeng
 * @CreateTime: 2024/7/31 13:40
 * @Annotation：认证流程 - 自拍照
 */
class MullaStepSelfieFm(): ProFm() {
    private var _binding: FmMullaStepSelfieBinding? = null
    private val binding get() = _binding ?: throw IllegalStateException(
        "Cannot access binding because it is null. Either the view hasn't been created yet, or it has already been destroyed."
    )
    private var stepItem: JSONObject? = null
    //是否选中删除信息,默认选中
    private var isSelectedDelete = true
    //本地预览地址
    private var faceImgPath = ""
    //拍摄的头像地址
    private var faceImgUrl = ""

    constructor(stepItem: JSONObject): this(){
        this.stepItem = stepItem
    }

    override fun getMullaRootView(inflater: LayoutInflater): View {
        _binding = FmMullaStepSelfieBinding.inflate(inflater)
        return binding.root
    }

    override fun initMullaView() {
        rootViewBinding.containerLayout.setBackgroundColor(Color.parseColor("#00000000"))
        stepItem?.let {
            _binding?.textStepTitle?.text = it.optString("showTitle")
        }
        isSelectedDelete = true
        showMullaSelifeDeleteInformationTips()
        showMullaSelfieBeforeView()
    }

    override fun initMullaListener() {
        _binding?.selifeDeleteTipsLayout?.setOnClickListener {
            isSelectedDelete = !isSelectedDelete
            showMullaSelifeDeleteInformationTips()
        }
        _binding?.viewMask?.setOnClickListener {
            if (XXPermissions.isGranted(requireContext(), Permission.CAMERA)){
                openMullaFlowSelfieCamera()
            } else {
                val item = takeMullaPerCameraItem()
                showMullaFlowPermissionReasonDialog(item)
            }
        }
        _binding?.imgRetake?.setOnClickListener {
            _binding?.viewMask?.callOnClick()
        }
        _binding?.imgView?.setOnClickListener {
            _binding?.viewMask?.callOnClick()
        }
        //提交
        _binding?.btnNext?.setOnClickListener {
            //开始人脸拍照
            if (faceImgUrl.isEmpty()){
                _binding?.viewMask?.callOnClick()
                return@setOnClickListener
            }
            HttpHelper.addMullaEventAction(MullaEventType.CLICK.MULLA_CLICK_STEP_SELFIE_CONFIRM_SUBMIT)
            // TODO: Step Next 批量埋点上报
            MullaBehaviorTracker.getInstance(context).reportImmediately(null)
            //提交
            val params = JSONObject().addCommonParams().addRandomParams().apply {
//                put("path", ApiService.API_PATH.MULLA_API_OCR_INFO_PATH)
                put("cardType","FACE")//证件类型（PASSPORT、IDCARD、DRIVING、FACE）
                put("faceImgUrl",faceImgUrl)//人脸图片
            }
            if (isSelectedDelete){
                showMullaDeleteInfoDialog(params)
            } else {
                val act = context as MullaStepsAct
                act.onMullaSubmitProcessAction(ApiService.API_PATH.MULLA_API_OCR_INFO_PATH,params)
            }
        }
    }

    override fun initMullaData() {
        HttpHelper.addMullaEventAction(MullaEventType.PAGE.MULLA_PAGE_STEP_SELFIE_START)

        val showApprovedKey1 = getString(R.string.step_selfie_upload_credit_limit_approved_tips_key1)
        val showApprovedKey2 = getString(R.string.step_selfie_upload_credit_limit_approved_tips_key2)
        val showApprovedText = String.format(getString(R.string.step_selfie_upload_credit_limit_approved_tips),showApprovedKey1,showApprovedKey2)
        val startApprovedIndex1 = showApprovedText.indexOf(showApprovedKey1)
        val startApprovedIndex2 = showApprovedText.indexOf(showApprovedKey2)
        val approvedTipsSpannable = SpannableString(showApprovedText)
        approvedTipsSpannable.setSpan(ForegroundColorSpan(Color.parseColor("#FF00CB48")), startApprovedIndex1, startApprovedIndex1 + showApprovedKey1.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        approvedTipsSpannable.setSpan(ForegroundColorSpan(Color.parseColor("#FF00CB48")), startApprovedIndex2, startApprovedIndex2 + showApprovedKey2.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        //加粗
        approvedTipsSpannable.setSpan(StyleSpan(Typeface.BOLD), startApprovedIndex1, startApprovedIndex1 + showApprovedKey1.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        approvedTipsSpannable.setSpan(StyleSpan(Typeface.BOLD), startApprovedIndex2, startApprovedIndex2 + showApprovedKey2.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        binding.textStepSelfieLimitApprovedTips.text = approvedTipsSpannable
    }

    /**
     * 人脸拍照
     */
    private val faceCameraResultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult ->
        when (result.resultCode) {
            RESULT_OK -> {
                val faceImgPath = result.data?.getStringExtra("imgLocalPath").toString()
                MullaLog.e(">>>>>>>>>face info ：$faceImgPath")
                val imgLocalPath = result.data?.getStringExtra("imgLocalPath").toString()
                val imgUrl = result.data?.getStringExtra("imgUrl").toString()
                showMullaSelfieAfterView(imgLocalPath,imgUrl)
            }
        }
    }

    /**
     * 显示未拍照View
     */
    private fun showMullaSelfieBeforeView(){
        _binding?.let { binding ->
            binding.imgView.setImageResource(R.mipmap.mulla_step_selfie_default_avater)
            binding.imgView.borderColor = Color.parseColor("#FF8027FF")
            binding.viewMask.visibility = View.GONE
            binding.imgRetake.visibility = View.GONE
            binding.textRetake.visibility = View.GONE
            binding.textClickTake.visibility = View.VISIBLE
            binding.btnNext.text = getString(R.string.step_selfie_take)
        }
    }

    /**
     * 显示拍照之后的View
     */
    private fun showMullaSelfieAfterView(imgPath: String, imgUrl: String){
        faceImgPath = imgPath
        faceImgUrl = imgUrl
        _binding?.let { binding ->
            ImageUtil.instance?.loadImageUrl(requireContext(),binding.imgView,faceImgPath)
            binding.imgView.borderColor = Color.parseColor("#FF8027FF")
            binding.viewMask.visibility = View.VISIBLE
            binding.imgRetake.visibility = View.VISIBLE
            binding.textRetake.visibility = View.VISIBLE
            binding.textClickTake.visibility = View.GONE
            binding.btnNext.text = getString(R.string.step_selfie_submit)
        }
    }

    private fun showMullaSelifeDeleteInformationTips(){
        when(isSelectedDelete){
            true -> {
                _binding?.imgSelifeDeleteTipsSelect?.setImageResource(R.mipmap.mulla_coupon_selected)
            }
            else -> {
                _binding?.imgSelifeDeleteTipsSelect?.setImageResource(R.mipmap.mulla_coupon_normal)
            }
        }
    }

    /**
     * 打开相机
     */
    private fun openMullaFlowSelfieCamera(){
        HttpHelper.addMullaEventAction(MullaEventType.CLICK.MULLA_CLICK_STEP_SELFIE_START_TAKE,"")
        faceCameraResultLauncher.launch(Intent(context, MullaCameraSelfieAct::class.java))
    }

    /**
     * 权限说明dialog
     */
    private fun showMullaFlowPermissionReasonDialog(data: JSONObject) {
        val reasonDialog = PermissionReasonDialog(context,"Selfie Page",object: PermissionReasonDialog.IDialogCallback{
            override fun onDenyClick() {
                HttpHelper.addMullaEventAction(MullaEventType.CLICK.MULLA_CLICK_PERMISSION_DENY,data.optString("permission"))
            }
            override fun onAgreeClick() {
                HttpHelper.addMullaEventAction(MullaEventType.CLICK.MULLA_CLICK_PERMISSION_AGREE,data.optString("permission"))
                requestMullaFlowPermission(data)
            }
        })
        reasonDialog.setCancelable(true)
        reasonDialog.setCanceledOnTouchOutside(true)
        reasonDialog.show()
        reasonDialog.showMullaFlowPermissionItem(data)
    }

    /**
     * 授权
     */
    private fun requestMullaFlowPermission(data: JSONObject){
        val permission = data.optString("permission")
        XXPermissions.with(requireContext())
            // 申请多个权限
            .permission(permission)
            .request(object: OnPermissionCallback {
                override fun onGranted(permissions: MutableList<String>, p1: Boolean) {
                    if (p1){
                        var permissionString = ""
                        permissions.forEach {
                            permissionString = "$permissionString$it,"
                        }
                        HttpHelper.addMullaEventAction(MullaEventType.CLICK.MULLA_CLICK_PERMISSION_SYSTEM_AGREE,permissionString.substring(0,permissionString.length - 1))
                        openMullaFlowSelfieCamera()
                    }
                }
                override fun onDenied(permissions: MutableList<String>, doNotAskAgain: Boolean) {
                    var permissionString = ""
                    permissions.forEach {
                        permissionString = "$permissionString$it,"
                    }
                    HttpHelper.addMullaEventAction(MullaEventType.CLICK.MULLA_CLICK_PERMISSION_SYSTEM_DENY,permissionString.substring(0,permissionString.length - 1))

                    XXPermissions.startPermissionActivity(requireContext(),permission)
                }
            })
    }

    private fun showMullaDeleteInfoDialog(params: JSONObject){
        val sendSuccessDialog = VerificationSendSuccessDialog(requireContext())
        sendSuccessDialog.setCancelable(true)
        sendSuccessDialog.setCanceledOnTouchOutside(false)
        sendSuccessDialog.show()
        sendSuccessDialog.showMullaSuccessTips(getString(R.string.step_selfie_delete_submit_success_tips))
        launch(Dispatchers.Main){
            delay(1500)
            if (isAdded && !requireActivity().isFinishing && sendSuccessDialog.isShowing) {
                sendSuccessDialog.dismiss()
            }

            val act = context as MullaStepsAct
            act.onMullaSubmitProcessAction(ApiService.API_PATH.MULLA_API_OCR_INFO_PATH,params)
        }
    }

    /**
     * camera
     */
    fun takeMullaPerCameraItem(): JSONObject{
        val item = JSONObject()
        item.put("isSystem",true)
        item.put("icon", R.mipmap.mulla_permission_item_camera_icon)
        item.put("permission",  Manifest.permission.CAMERA)
        item.put("title", getString(R.string.permission_camera_title))
        val msgArray = JSONArray()
        val obj1 = JSONObject()
        obj1.put("title", "")
        obj1.put("des", getString(R.string.permission_camera_desc1))
        msgArray.put(obj1)

        val obj2 = JSONObject()
        obj2.put("title", "")
        obj2.put("des", getString(R.string.permission_camera_desc2))
        msgArray.put(obj2)

        val obj3 = JSONObject()
        obj3.put("title", "")
        obj3.put("des", getString(R.string.permission_camera_desc3))
        msgArray.put(obj3)

        item.put("msgList",msgArray)
        return item
    }

    override fun onDestroy() {
        super.onDestroy()
        HttpHelper.addMullaEventAction(MullaEventType.PAGE.MULLA_PAGE_STEP_SELFIE_END)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}